#!/bin/bash

# hc-host-assemble host-bitcode host-object (options)

# enable bash debugging
KMDBSCRIPT="${KMDBSCRIPT:=0}"

# dump the LLVM bitcode
KMDUMPLLVM="${KMDUMPLLVM:=0}"

if [ $KMDBSCRIPT == "1" ]
then
  set -x
fi

BINDIR=$(dirname $0)
CLANG=$BINDIR/clang
OPT=$BINDIR/opt
LLVM_AS=$BINDIR/llvm-as
LLVM_DIS=$BINDIR/llvm-dis
LIBPATH=$BINDIR/../lib

if [ "$#" -lt 2 ]; then
  echo "Usage: $0 kernel-bitcode object (options)" >&2
  exit 1
fi

if [ ! -f $1 ]; then
  echo "kernel-bitcode $1 is not valid" >&2
  exit 1
fi

CXXFLAGS=
# Pass down compiler options
if [ "$#" -ge 2 ]; then
  num=2
  while [ $num -lt $# ]
  do
    (( num++ ))
    ARG="${!num}"
    CXXFLAGS=$CXXFLAGS' '"\"$ARG\""
  done
fi

CO="-c -o"

TEMP_DIR=`mktemp -d`
BASENAME=`basename $2`
TEMP_NAME="$TEMP_DIR/$BASENAME"

$LLVM_DIS $1 -o $TEMP_NAME.ll
if [ $KMDUMPLLVM == "1" ]; then
  cp $TEMP_NAME.ll ./dump.host_input.ll
fi
$OPT -load $LIBPATH/LLVMDirectFuncCall.so -redirect -host < $TEMP_NAME.ll 2>$TEMP_NAME.host_redirect.ll >/dev/null
if [ $KMDUMPLLVM == "1" ]; then
  cp $TEMP_NAME.host_redirect.ll ./dump.host_redirect.ll
fi
if [[ -s $TEMP_NAME.host_redirect.ll ]]; then
  $LLVM_AS $TEMP_NAME.host_redirect.ll -o $TEMP_NAME.host_redirect.bc
  eval "$CLANG $CXXFLAGS $TEMP_NAME.host_redirect.bc $CO $2"
else
  ln -s $1 $1.bc
  eval "$CLANG $CXXFLAGS $1.bc $CO $2"
fi

rm -f $TEMP_NAME.* $1.bc
rmdir $TEMP_DIR
